package com.zranger.locationdevice.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * 客户端测试用处理器
 *
 * @author kent
 * @date 15-9-2.
 */
public class TestClientHandler extends ChannelInboundHandlerAdapter {

    /**
     * 建立连接后发送测试内容
     *
     * @param ctx
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {

        for (int j = 0; j < 50; j++) {
            ByteBuf byteBuf = Unpooled.buffer(256);

            /*for (int i = 0; i < 8; i++) {
                if (i == 4) {
                    byteBuf.writeByte(10);
                    byteBuf.writeByte(0);
                }
                byte b = (byte) Integer.parseInt("a7", 16);

                byteBuf.writeByte(b);
            }*/

            String msg = "a70a7a004c539876543210123540460019634614740089860114838023588160343630303100f1fb09002c016e141e020001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";

            for (int i = 0; i < msg.length(); i+=2) {
                byte b = (byte) Integer.parseInt(msg.substring(i,i+2),16);
                byteBuf.writeByte(b);
            }

            ctx.writeAndFlush(byteBuf);
        }
    }

    /**
     * 读取服务端返回内容
     * 这里未对服务端返回的内容再做粘包和拆包处理，所以客户这里显示的返回内容有可能会出现粘包以及拆包现象
     *
     * @param ctx
     * @param msg
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {

        ByteBuf byteBuf = (ByteBuf) msg;
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes, 0, byteBuf.readableBytes());

        System.out.println(new String(bytes));

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        cause.printStackTrace();
        ctx.close();
    }

    public static void main(String[] args) {

        String msg = "a70a7a004c539876543210123540460019634614740089860114838023588160343630303100f1fb09002c016e141e020001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";

        for (int i = 0; i < msg.length(); i+=2) {
            System.out.println(msg.substring(i, i + 2));
        }
    }

}
